﻿using System;
using System.IO;
using LockerRack.Exceptions;
using LockerRack.Helpers;
using LockerRack.Interfaces;
using TasksLib.DrawerStuff.Serializable;

namespace TasksLib.DrawerStuff
{
    public class TaskXmlFile : IDrawerFileStuff
    {
        public SerializableTask Task
        {
            get
            {
                if(PropertyBag is SerializableTask)
                    return PropertyBag;

                return null;
            }
        }

        public Guid Id
        {
            get
            {
                if (Task != null)
                    return Task.GuidId;

                return Guid.Empty;
            } 
            set{}
        }

        public TaskXmlFile()
        {
            PropertyBag = new SerializableTask();
        }

        public dynamic PropertyBag { get; set; }

        public bool Load(string path, out LockerException lex)
        {
            var serializer = new Helpers.DataSerializer<SerializableTask>();
            var task = serializer.ReadFile(path, out lex);
            if (task != null && lex == null)
                PropertyBag = task;

            return task != null;
        }

        public bool Save(string path, out LockerException lex)
        {
            lex = null;
            if (PropertyBag == null)
                return false;

            try
            {
                var filename = string.Format("{0}{1}", Task.GuidId, Constants.TASK_FILE_NAME);
                filename = Path.Combine(path, filename);
                var serializer = new Helpers.DataSerializer<SerializableTask>();
                return serializer.WriteFile(filename, Task, out lex);
            }
            catch (Exception ex)
            {
                lex = new LockerException("Can't save", ex);
            }

            return false;
        }

        public bool CreateDefaulContent(object data, out LockerException lex)
        {
            lex = new LockerException("NotImplementedException", new NotImplementedException());
            return false;
        }
        
        public void Dispose()
        {
            PropertyBag = null;
        }
    }
}
